package com.yanqu.road.server.cmd.activity.washe.cross;

import com.yanqu.road.entity.activity.washe.data.WasheLastResultData;
import com.yanqu.road.entity.enums.washe.eWasheColorType;
import com.yanqu.road.entity.enums.washe.eWasheHonorMomentType;
import com.yanqu.road.entity.enums.washe.eWasheModeType;
import com.yanqu.road.entity.enums.washe.eWasheOperateType;
import com.yanqu.road.entity.enums.washe.eWasheSkillType;
import com.yanqu.road.message.YanQuMessage;
import com.yanqu.road.pb.activity.WasheProto;
import com.yanqu.road.server.command.Cmd;
import com.yanqu.road.server.command.Command;
import com.yanqu.road.server.gameplayer.GamePlayer;
import com.yanqu.road.server.gameplayer.module.activity.washe.WasheModule;
import com.yanqu.road.server.manger.activity.washe.WasheMgr;
import com.yanqu.road.server.manger.player.GamePlayerMgr;
import com.yanqu.road.server.protocol.ClientProtocol;
import com.yanqu.road.server.protocol.GameProtocol;
import io.netty.channel.ChannelHandlerContext;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Cmd(code = GameProtocol.S_WASHE_NOTICE_FROM_CROSS, desc = "")
public class WasheNoticeFromCrossCmd implements Command {

    @Override
    public void execute(ChannelHandlerContext ctx, YanQuMessage yanQuMessage) throws Exception {
        long userId = yanQuMessage.getPlayerId();
        WasheProto.WasheBatchSyncNoticeRespMsg respMsg = WasheProto.WasheBatchSyncNoticeRespMsg.parseFrom(yanQuMessage.getBytes());

        GamePlayer onlinePlayer = GamePlayerMgr.getOnlinePlayer(userId);
        if (onlinePlayer == null) {
            noPlayerHandle(userId, respMsg);
        } else {
            hasPlayerHandle(onlinePlayer, respMsg);
        }
    }

    // 玩家不在内存里
    private void noPlayerHandle(long userId, WasheProto.WasheBatchSyncNoticeRespMsg respMsg) {
        for (WasheProto.WasheSyncNoticeRespMsg msg : respMsg.getMsgListList()) {
            // 处理游戏结束
            if (msg.getType() == eWasheOperateType.GameOver.getValue()) {
                // 移除ping
                WasheMgr.removePing(userId);
                // 保存结果
                WasheMgr.addLastResultData(userId, msg.getOver(), false);
                return;
            }
        }
    }

    // 玩家在内存里
    private void hasPlayerHandle(GamePlayer player, WasheProto.WasheBatchSyncNoticeRespMsg respMsg) {
        WasheProto.WasheBatchSyncNoticeRespMsg.Builder builder = respMsg.toBuilder();

        // 【修改历史记录】
        if (respMsg.getModeId() != eWasheModeType.FriendPk.getValue()
                && respMsg.getModeId() != eWasheModeType.Practice.getValue()) {
            try {
                checkHistoryChange(player, respMsg.getMsgListList());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        // 【处理结束】
        for (int i = 0; i < builder.getMsgListCount(); i++) {
            WasheProto.WasheSyncNoticeRespMsg msg = builder.getMsgList(i);
            if (msg.getType() == eWasheOperateType.GameOver.getValue()) {
                // 移除ping
                WasheMgr.removePing(player.getUserId());
                // 处理结果
                WasheProto.WasheGameOverMsg overMsg = msg.getOver();
                WasheProto.WasheGameOverMsg.Builder overBuilder = player.getModule(WasheModule.class).gameOverAction(overMsg);
                WasheProto.WasheSyncNoticeRespMsg.Builder noticeBuilder = msg.toBuilder();
                noticeBuilder.setOver(overBuilder);
                builder.setMsgList(i, noticeBuilder);
                // 保存结果
                WasheMgr.addLastResultData(player.getUserId(), overBuilder.build(), true);
                // 小概率情况打个日志，有问题好找
                if (GamePlayerMgr.getOnlinePlayer(player.getUserId()) == null) {
                    WasheLastResultData lastResultData = WasheMgr.getLastResultData(player.getUserId());
                    WasheMgr.getLogger().error("hasPlayerHandle finish and player remove map... userId {}, msgData {}",
                            player.getUserId(), lastResultData == null ? "null" : lastResultData.getMsgData());
                }
                break;
            }
        }

        player.sendPacket(ClientProtocol.U_WASHE_NOTICE, builder);
    }

    // 历史记录变化
    private void checkHistoryChange(GamePlayer player, List<WasheProto.WasheSyncNoticeRespMsg> msgList) {

        Map<Integer, Long> typeValueMap = new HashMap<>();

        for (WasheProto.WasheSyncNoticeRespMsg msg : msgList) {

            if (msg.getType() == eWasheOperateType.Move.getValue() ||
                    msg.getType() == eWasheOperateType.UseCard.getValue() ||
                    msg.getType() == eWasheOperateType.UseSkill.getValue()) {

                // 跳过不是自己操作的
                WasheProto.WasheOperateResultMsg operate = msg.getOperate();
                int selfSide = operate.getGameData().getSelfData().getSide();
                if (operate.getSide() != selfSide) {
                    continue;
                }

                int redColor = selfSide == 1 ? eWasheColorType.Blue.getValue() : eWasheColorType.Red.getValue();
                int blueColor = selfSide == 1 ? eWasheColorType.Red.getValue() : eWasheColorType.Blue.getValue();

                // 统计的数据
                long consecutiveEliminate = 0;
                int redCount = 0;
                int blueCount = 0;

                for (WasheProto.WasheShowMsg showMsg : operate.getShowList()) {
                    for (WasheProto.WasheRoundResultMsg roundResultMsg : showMsg.getRoundResultList()) {
                        if (roundResultMsg.getType() == 1) { // 1：正常消除
                            consecutiveEliminate++;
                            for (WasheProto.WasheStageResultMsg stageResultMsg : roundResultMsg.getStageResultList()) {
                                for (WasheProto.WasheBlockMsg blockMsg : stageResultMsg.getBlockListList()) {
                                    if (blockMsg.getColor() == redColor) {
                                        redCount++;
                                    } else if (blockMsg.getColor() == blueColor) {
                                        blueCount++;
                                    }
                                }
                            }
                        }
                    }
                }

                // 处理数据
                if (msg.getType() != eWasheOperateType.UseCard.getValue() &&
                        consecutiveEliminate > typeValueMap.getOrDefault(eWasheHonorMomentType.ConsecutiveEliminate.getIntValue(), 0L)) {
                    typeValueMap.put(eWasheHonorMomentType.ConsecutiveEliminate.getIntValue(), consecutiveEliminate);
                }
                if (blueCount > 0) {
                    WasheMgr.addTempHistoryValue(typeValueMap, eWasheHonorMomentType.EliminateBlueCount, blueCount);
                }
                if (redCount > 0) {
                    WasheMgr.addTempHistoryValue(typeValueMap, eWasheHonorMomentType.EliminateRedCount, redCount);
                }
                if (msg.getType() == eWasheOperateType.UseSkill.getValue() && operate.getSkillId() == eWasheSkillType.Skill_1002.getValue()) {
                    WasheMgr.addTempHistoryValue(typeValueMap, eWasheHonorMomentType.UseHammerTimes, 1L);
                }
                if (msg.getType() == eWasheOperateType.UseCard.getValue()) {
                    WasheMgr.addTempHistoryValue(typeValueMap, eWasheHonorMomentType.Collect_OneGameUseCardTimes, 1L);
                }

            }

        }

        // 历史记录
        if (typeValueMap.size() > 0) {
            player.getModule(WasheModule.class).changeHistory(typeValueMap);
        }
    }
}
